import { routers as constRouters } from '@/router/index'
import { cloneDeep } from 'lodash'

const usePermissionStore = defineStore(
  'permission',
  {
    state: () => ({
      routers: []
    }),
    actions: {
      // 权限控制路由
      generateRoutes() {
        const permissions = JSON.parse(localStorage.getItem('userInfo'))?.permissions.permissions || []
        const newRouters = cloneDeep(constRouters)
        return new Promise(resolve => {
          // 路由权限控制，目前只做到第三层菜单级别，后续如果有四级菜单，需要再进行遍历判断
          newRouters.map((item) => {
            if (permissions.includes(item.name)) item.hidden = false
            if (item.children) {
              item.children.map((chItem) => {
                if (permissions.includes(chItem.name)) chItem.hidden = false
                if (chItem.children) {
                  chItem.children.map((graItem) => {
                    if (permissions.includes(graItem.name)) graItem.hidden = false
                  })
                }
              })
            }
          })
          this.routers = newRouters
          resolve()
        })
      },
      ResetRouters() {
        this.routers = []
      }
    }
  })

export default usePermissionStore
